<?php

namespace app\apiadmin\controller\aliyun;

use app\apilive\model\public\PlatformSmsVoiceExecuteDataModel;
use app\common\utils\Res;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use app\common\controller\BaseController;

class AliCallback extends BaseController
{
    public function __construct()
    {
    }

    //回调接收
    public function smsCallback()
    {
        $data = json_decode(Request::getInput(), true);
        try {
            DB::table('xh_open_platform_sms_callback')->insertAll($data);
        } catch (\Exception $e) {
            Log::error('[语音电话回调：入库失败]'.$e->getMessage());
        }
        DB::table('xh_open_platform_sms_callback')->insertAll($data);
        foreach ($data as $datum) {
            //$datum = json_encode($datum, JSON_UNESCAPED_UNICODE);
            //$this->redis->lPush('ali:sms:callback', $datum);
            try {
                if (!empty($datum) && $datum['biz_id']) {
                    $sendDesc = DB::table('xh_open_platform_sms_voice_execute')->where(['biz_id'=>$datum['biz_id']])->find();
                    if (!empty($sendDesc) && $sendDesc['source'] == 'order') {
                        if ($datum['success'] == 'DELIVERED') {
                            $save['receive_sms'] = 1;
                        } else {
                            $save['receive_sms'] = 2;
                        }
                        $save['report_time'] = $datum['report_time'];
                        DB::table('order_'.$sendDesc['qiyeid'])->where(['order_num'=>$sendDesc['source_id']])->save($save);
                    }
                }
            } catch (\Exception $e) {
                Log::error('[短信回调：解析数据失败]'.$e->getMessage());
            }
        }
        return Json([
            'code'=>0,
            'msg'=>'成功',
        ]);

    }
    
    // 语音电话回调
    public function voiceTelCallback()
    {
        $data = json_decode(Request::getInput(), true);
        try {
            DB::table('xh_open_platform_voice_callback')->insertAll($data);
        } catch (\Exception $e) {
            Log::error('[语音电话回调：入库失败]'.$e->getMessage());
        }
        return Json([
            'code'=>0,
            'msg'=>'成功',
        ]);
    }
    
    /**
     * 发送短信
     * @link 
     * @param string $signature 签名
     * @param string $template 模板ID
     * @param string $mobile 手机号
     * @param string $stats 模板参数
     * @return bool
     * @meta 
     * */
    public static function sendSms($signature, $template, $mobile, $stats)
    {
        #生成签名
        $sign = self::generateSignature($signature, $template, $mobile, $stats);
        #拼接请求链接
        $url = "https://dysmsapi.aliyuncs.com/?Signature=".$sign;

        try {
            $content = self::curlRuqust($url);
            PlatformSmsVoiceExecuteDataModel::create(['result'=>$content, 'create_time'=>date('Y-m-d H:i:s')]);
            return json_decode($content,true);
        } catch( \Exception $e) {
            return false;
        }
    }

    //生成签名(含参数)
    public static function generateSignature($signature, $template, $mobile, $stats)
    {
        $Timestamp = gmdate("Y-m-d\TH:i:s\Z");

        #系统参数
        $sysdata = [
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => self::uuid(),
            'AccessKeyId' => env('ali.gitAccessKeyId', 'LTAI5tEjCuzTNY5feKMXFrLv'),
            'SignatureVersion' => "1.0",
            'Timestamp' => $Timestamp,
            'Format' => 'json',
        ];
        #业务API参数
        $apidata = self::apidata($signature, $template, $mobile, $stats);

        #合并参数
        $datas = array_merge($sysdata, $apidata);

        #升序排列
        ksort($datas);

        #拼接加密字符串
        $sortedQueryStringTmp  = "";
        foreach($datas as $key=>$val)
        {
            $sortedQueryStringTmp  .= "&".$key."=".self::encode($val);
        }
        $stringToSign = "GET&%2F&" . self::encode(substr($sortedQueryStringTmp, 1));

        #加密转码
        $encipherTranscoding = base64_encode(hash_hmac("sha1", $stringToSign, env('ali.accessSecret', 'TVzEn6y3K6AVQgoBDnzaejPk7Nw9yL') . "&",true));

        #生成签名
        $sign = self::encode($encipherTranscoding);
        return $sign.$sortedQueryStringTmp;
    }

    //业务参数整合
    public static function apidata($signature, $template, $mobile, $stats)
    {
        if (!is_array($signature)) {
            $signature = [$signature];
        }
        if (!is_array($mobile)) {
            $mobile = [$mobile];
        }
        if (is_array($stats)) {
            if (count($mobile) == 1) {
                $stats = [$stats];
            }
        } else {
            $stats = [$stats];
        }
        $apidata = [
            'Action' =>  'SendBatchSms',
            'Version' => '2017-05-25',
            'RegionId' => 'cn-hangzhou',
            'PhoneNumberJson' => json_encode($mobile),
            'SignNameJson' => json_encode($signature),
            'TemplateParamJson' => json_encode($stats),
            'TemplateCode' => $template,
        ];
        Log::write("------发短信-----" . json_encode($apidata));
        return $apidata;
    }

    //阿里云短信对应转码替换
    private static function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

    //PHP生成 UUID
    public static function uuid()
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr ( $chars, 0, 8 ) . '-'
            . substr ( $chars, 8, 4 ) . '-'
            . substr ( $chars, 12, 4 ) . '-'
            . substr ( $chars, 16, 4 ) . '-'
            . substr ( $chars, 20, 12 );
        return $uuid ;
    }

    //curl请求
    private static function curlRuqust($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));
        if(substr($url, 0,5) == 'https')
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $rtn = curl_exec($ch);
        if($rtn === false)
        {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);
        return $rtn;
    }


}